package defense.physics;

public class Vec2f {
	/**
	 * the x-coordinate
	 */
	public float x;

	/**
	 * the y-coordinate
	 */
	public float y;

	public Vec2f() {
		x = y = 0;
	}

	public Vec2f(float x, float y) {
		this.x = x;
		this.y = y;
	}

	/**
	 * adds another vector to this one
	 */
	public void add(Vec2f b) {
		this.x += b.x;
		this.y += b.y;
	}

	/**
	 * calculates the sum of two vectors
	 */
	public Vec2f plus(Vec2f b) {
		return new Vec2f(x + b.x, y + b.y);
	}

	/**
	 * subtracts another vector from this one
	 */
	public void sub(Vec2f b) {
		this.x -= b.x;
		this.y -= b.y;
	}

	/**
	 * subtracts another vector from this one and returns the result in a new
	 * vector.
	 */
	public Vec2f minus(Vec2f b) {
		return new Vec2f(x - b.x, y - b.y);
	}

	/**
	 * scales the vector
	 */
	public void mult(float scalar) {
		this.x *= scalar;
		this.y *= scalar;
	}

	/**
	 * multiplies the vector
	 */
	public Vec2f times(float scalar) {
		return new Vec2f(this.x * scalar, this.y * scalar);
	}

	/**
	 * calculates the dot product between two vectors
	 */
	public float dot(Vec2f b) {
		return this.x * b.x + this.y * b.y;
	}

	/**
	 * calculates the magnitude of the vector
	 */
	public float mag() {
		return (float) Math.sqrt(x * x + y * y);
	}

	/**
	 * calculates the square of the magnitude. This can be used to compare
	 * lengths of two vectors, since it performs slightly faster than
	 * {@link #mag()}
	 */
	public float magSq() {
		return x * x + y * y;
	}

	/**
	 * scales the vector to the length 1
	 */
	public void normalize() {
		float invMag = 1.0f / mag();
		mult(invMag);
	}

	public float distanceTo(Vec2f pos) {
		float xDiff = pos.x - x;
		float yDiff = pos.y - y;
		return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);
	}

	@Override
	public String toString() {
		return "Vec2f [x=" + x + ", y=" + y + "]";
	}
}
